#include "loginwidget.h"
#include "ui_loginwidget.h"
#include <QDebug>
#include <QMessageBox>
#include <QElapsedTimer>

LoginWidget::LoginWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoginWidget),
    m_lastErrorTime(QDateTime::fromSecsSinceEpoch(0))
{
    ui->setupUi(this);
    m_pDatabaseManager = DatabaseManager::instance();
    m_pUserManager = UserManager::instance();

//    if (!m_pDatabaseManager->connectToServer()) {
//        QTimer::singleShot(0, this, [this](){ emit sendMessage("数据库连接失败"); });
//    }


    connect(ui->loginBtn, &QPushButton::clicked, this, &LoginWidget::onLoginClicked);
    connect(ui->btnGotoRegister, &QPushButton::clicked, this, [this]() {
        emit display(1);
    });
    connect(ui->btnGetBack, &QPushButton::clicked, this, [this]() {
        emit display(2);
    });

    if(!DatabaseManager::instance()->isConnected()) {
        emit sendMessage("数据库未连接，请检查服务器状态");
        return;
    }
}

void LoginWidget::onLoginClicked()
{
    if(!DatabaseManager::instance()->isConnected()) {
        emit sendMessage("数据库未连接，请检查服务器状态");
        return;
    }

    QString inputUserName = ui->lineEditUserName->text().trimmed();
    QString inputPassword = ui->lineEditPassword->text().trimmed();
    qDebug() << "Raw password input (UTF-8):" << inputPassword.toUtf8().toHex();

    // 输入验证
    if (inputUserName.isEmpty() || inputPassword.isEmpty()) {
        static QString lastEmptyError;
        QString currentError = "用户名和密码不能为空";
        return;
    }

    // 频率限制
    static QElapsedTimer loginTimer;
    if (loginTimer.isValid() && loginTimer.elapsed() < 1000) {
        emit sendMessage("操作过于频繁，请稍后再试");
        return;
    }
    loginTimer.restart();

    std::pair<bool, UserManager::UserError> loginResult = m_pUserManager->validateLogin(inputUserName, inputPassword);
        bool success = loginResult.first;
        UserManager::UserError error = loginResult.second;

        if (success) {
            // 登录成功逻辑
            QString role = m_pUserManager->getUserRole(inputUserName);
            m_pUserManager->setCurrentUser(inputUserName, role);
            m_pUserManager->setCurrentUserRole(role);
            emit sendMessage("登录成功");
            emit userDisplay(role == "admin" ? 0 : 1);
            display(3);
        } else {
            // 登录失败逻辑
            QString errorMsg;
            switch (error) {
                case UserManager::UserError::UserNotFound:
                    errorMsg = "用户名不存在";
                    break;
                case UserManager::UserError::WrongCredentials:
                    errorMsg = "密码错误";
                    break;
                default:
                    errorMsg = "登录失败，请稍后再试";
                    break;
            }
            emit sendMessage(errorMsg);

            // 仅在明确失败时记录日志（且确保表存在）
            if (error != UserManager::UserError::ConnectionError) {
                QString logContent = QString("登录失败: %1 (用户名: %2)").arg(errorMsg).arg(inputUserName);
                LogManagement::log(logContent, LogManagement::OPERATION_LOG, LogManagement::LOG_ERROR);
            }
        }
    }

void LoginWidget::setUserManager(UserManager* userManager)
{
    if (m_pUserManager) {
        m_pUserManager->deleteLater();
    }
    m_pUserManager = userManager;
}

LoginWidget::~LoginWidget()
{
    delete ui;
}



